-- 导入响应式api
local r = require "ch7.r"

local reactive = r.reactive
local ref = r.ref
local effect = r.effect

-- print("rApi", reactive, ref, effect)


local function createRenderer(...)
    local createElement, insert, setElementText = ...
    -- print("options", createElement, insert, setElementText)

    local function mountElement(vnode, container)
        -- type
        local el = createElement(vnode.type)
        -- children
        if (type(vnode.children) == "string") then
            setElementText(el, vnode.children)
        end
        -- parent
        insert(el, container)
    end

    local function patch(n1, n2, container)
        if(not n1)then
            mountElement(n2,container)
        else 

        end
    end

    local function render(vnode, container)
        if (vnode) then
            -- 挂载新的 比较
            patch(container._vnode, vnode, container)
        else
            -- 卸载旧的
            if (container._vnode) then
                container["content"] = ""
            end
        end
        -- 记录旧的
        container._vnode = vnode
        print("container", container._vnode)
    end

    return {
        render = render
    }
end

local renderer = createRenderer(
-- createElement
    function(tag)
        print("createElement", tag)
        return { tag }
    end,
    -- insert
    function(el, parent)
        print("insert", parent, el)
        parent["children"] = el
    end,
    -- setElementText
    function(el, text)
        print("set text", el, text)
        el["text"] = text
    end
);

-- print("render",renderer.render)

local container = { type = "root" }
local vnode = {
    type = "h1",
    children = "hello"
}

renderer.render(vnode, container)
